from django.shortcuts import render
from .serializers import *
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from .models import *
# Create your views here.
class Public(generics.CreateAPIView):
    # 兼容PUT和DELETE请求
    def post(self, request, *args, **kwargs):
        if request.data.get('_method') == 'PUT':
            return self.update(request, *args, **kwargs)
        elif request.data.get('_method') == 'DELETE':
            return self.destroy(request, *args, **kwargs)
    #获取一个操作对象
    def get_one_obj(self, queryset, model_name, **kwargs):
        try:
            obj = queryset.filter(id=kwargs.get('id'))
            return obj
        except model_name.DoesNotExist:
            return None
    #定义函数完成外键数据的绑定
    def bind_forignkey(self, source, destination, forign_key, many=False):
        result = False
        if many and (source is not None):
            getattr(destination, forign_key).add(source)
            result = True
        elif source is not None:
            obj = getattr(destination, forign_key)
            obj = source
            result = True
        destination.save()
        return result

class ListDatas(generics.ListCreateAPIView):
    def get(self, request, *args, **kwargs):
        page = int(request.GET.get('page'))
        datas = self.queryset[(page-1)*10:10 * page]
        ser = self.serializer_class(datas, many=True)
        totle_page = int(self.queryset.count()/10) if self.queryset.count() % 10 == 0 else int(self.queryset.count()/10)+1
        return Response({'data':ser.data, 'page':totle_page}, status=status.HTTP_200_OK)

class Questions(ListDatas):
    queryset = Subject.objects.all()
    serializer_class = SubjectSerializer

class Question(generics.RetrieveUpdateDestroyAPIView, Public):
    queryset = Subject.objects.all()
    serializer_class = SubjectSerializer

    def get(self, request, *args, **kwargs):
        one_q = self.get_one_obj(self.queryset, Subject, **kwargs)
        if one_q:
            ser = SubjectSerializer(one_q)
            return Response(ser.data, status=status.HTTP_200_OK)
        else:
            return Response({'error': '该题目不存在'}, status=status.HTTP_404_NOT_FOUND)
    #完成题目和对应评论数据的绑定
    def update(self, request, *args, **kwargs):
        one_q = self.get_one_obj(self.queryset, Subject, **kwargs)
        ser = SubjectSerializer(one_q, data=request.data)
        if ser.is_valid():
            ser.save()
            #完成外键数据的绑定
            result = True
            if request.data.get('comment_id') is not None:
                one_c = Comment.objects.filter(id=request.data.get('comment_id')).first()
                result = self.bind_forignkey(one_c, one_q, 'comment')
            if result:
                return Response(ser.data, status=status.HTTP_200_OK)
            else:
                return Response({'error':'forign_key bind failed'}, status=status.HTTP_400_BAD_REQUEST)
        return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)

class Collections(ListDatas):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer

class OneCollection(generics.RetrieveUpdateDestroyAPIView, Public):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer

class Comments(ListDatas):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

class OneComment(generics.RetrieveUpdateDestroyAPIView, Public):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

    def update(self, request, *args, **kwargs):
        one_c = self.get_one_obj(self.queryset, Comment, **kwargs)
        ser = CommentSerializer(one_c, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data, status=status.HTTP_200_OK)
        return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)

class Users(ListDatas):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class OneUser(generics.RetrieveUpdateDestroyAPIView, Public):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class SubjectRoles(ListDatas):
    queryset = SubjectRole.objects.all()
    serializer_class = SubjectRoleSerializer

class OneSubjectRole(generics.RetrieveUpdateDestroyAPIView, Public):
    queryset = SubjectRole.objects.all()
    serializer_class = SubjectRoleSerializer

